package com.dw.love.dwade.view;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.dw.love.dwade.R;
import com.dw.love.dwade.common.FileManager;
import com.dw.love.dwade.utils.LruCachePicUtils;
import com.github.chrisbanes.photoview.PhotoView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by luozizhao on 2018/6/19.你
 */

public class PhotoViewActivity extends AppCompatActivity {

    @BindView(R.id.pv_picture)
    PhotoView pvPicture;
    @BindView(R.id.iv_download)
    ImageView ivDownload;
    @BindView(R.id.iv_gif_picture)
    ImageView ivGifPicture;
    private String path;
    private final static int REQUESTCODE = 1;
    private final static String TAG = "PhotoViewActivity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photoview_layout);
        ButterKnife.bind(this);
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            path = intent.getStringExtra("path");
        }
        if (path != null) {
            if (path.endsWith(".jpg")) {
                Glide.with(this).load(path).asBitmap().into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        pvPicture.setImageBitmap(resource);
                        LruCachePicUtils.getInstants().setBitmap(path, resource);
                    }
                });
            } else if (path.endsWith(".gif")) {
                Glide.with(this).load(path).asGif().into(pvPicture);
            }
        }
    }


    @OnClick({R.id.pv_picture, R.id.iv_download})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.pv_picture:
                finish();
                break;
            case R.id.iv_download:
                //运行时权限判断
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        saveFile();
                    } else {
                        //request
                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUESTCODE);
                    }
                } else {
                    saveFile();
                }
                break;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUESTCODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                saveFile();
            } else {
                ToastUtils.showShort("请开启读写权限");
            }
        }
    }

    private void saveFile() {
        if (path.endsWith(".jpg")) {
            String result = FileManager.getInstance(this).addBitmapToCache(path, LruCachePicUtils.getInstants().getBitmap(path));
            if (TextUtils.isEmpty(result)) {
                ToastUtils.showShort("保存失败");
            } else {
                Log.d(TAG, "saveFile: path:" + result);
                ToastUtils.showShort(String.format("成功保存至：%s 目录下", result));
                //key: 使照片可以在相册中找到
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(result))));
            }
        } else if (path.endsWith(".gif")) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    String glidePicPath = getImagePath(path);


                    if (path.startsWith("http://") || path.startsWith("https://")) {
                        int indexOf = path.lastIndexOf("/");
                        path = path.substring(indexOf, path.length());
                    }

                    String newPicPath = FileManager.getInstance(PhotoViewActivity.this).getBitmapEtrFilePath() + path;
                    copyFile(glidePicPath, newPicPath);
                    PhotoViewActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(newPicPath))));
                }
            }).start();
        }

    }


    /**
     * Glide 获得图片缓存路径
     */
    private String getImagePath(String imgUrl) {
        String path = null;
        FutureTarget<File> future = Glide.with(this)
                .load(imgUrl)
                .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
        try {
            File cacheFile = future.get();
            path = cacheFile.getAbsolutePath();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return path;
    }

    public void copyFile(String oldPath, final String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showShort(String.format("成功保存至：%s 目录下", newPath));
                }
            });
        } catch (Exception e) {
            e.printStackTrace();

        }

    }
}
